﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using OpenNETCF.Security.Cryptography;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using FFWinMobile.Properties;

namespace FFWinMobile
{
    public partial class frmUserForm : Form
    {
        public frmUserForm()
        {
            InitializeComponent();
        }
        string username;
        public frmUserForm(string userName)
        {
            username = userName;
            InitializeComponent();
        }

        private void frmUserForm_Load(object sender, EventArgs e)
        {
            pnlFeeds.Height = (this.Height - 41);
            if (GF.Giris)
            {
                ReadUserFeeds();
            }
            else
            {
                frmLogin frm = new frmLogin();
                DialogResult dr = frm.ShowDialog();
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                if (dr == DialogResult.OK)
                {
                    this.Show();
                    ReadUserFeeds();
                }
                else
                {
                    Application.Exit();
                }
            }
          
        }
        private void ReadUserFeeds()
        {

            ReadUserFeeds(null,0);

        }
        private void ReadUserFeeds(string id, int curPos)
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            pnlFeeds.Controls.Clear();
            string response;
            if (id == null)
                response = FF.ReadUserFeed(username, curPos);
            else
                response = FF.ReadUserFeed(FF.ReadFeedWith.WithCommentsAndLikes, username, curPos);
            if (response != "forbidden")
            {
                JObject j = JObject.Parse(response);
                JArray entries = (JArray)j["entries"];
                int x = 3, y = 3;
                Rectangle rect = pnlFeeds.ClientRectangle;
                rect.Width -= 20;

                Label user = new Label();
                user.Location = new Point(x, y);
                user.Font = new Font(FontFamily.GenericSansSerif, 12f, FontStyle.Bold);
                user.ForeColor = Color.Black;

                user.Text = j["name"].Value<string>();
                this.Text = user.Text;
                user.Width = rect.Width;
                user.Height = CFMeasureString.MeasureString(user, user.Text, rect).Height;
                y += 1;
                y += user.Size.Height;
                pnlFeeds.Controls.Add(user);
                if (j["description"] != null)
                {
                    Label userDesc = new Label();
                    userDesc.Location = new Point(x, y);
                    userDesc.Font = new Font(FontFamily.GenericSansSerif, 8f, FontStyle.Italic);
                    userDesc.ForeColor = Color.Black;
                    userDesc.Text = j["description"].Value<string>();
                    userDesc.Width = rect.Width;
                    userDesc.Height = CFMeasureString.MeasureString(userDesc, userDesc.Text, rect).Height;
                    y += 1;
                    y += userDesc.Size.Height;
                    pnlFeeds.Controls.Add(userDesc);
                }

                foreach (JToken command in j["commands"])
                {
                    if (command.Value<string>() == "unsubscribe")
                    {
                        Button btnUnsubcribe = new Button();
                        btnUnsubcribe.Text = Properties.Resources.UNSUBCRIBE_TEXT;
                        btnUnsubcribe.Tag = j["id"].Value<string>();
                        btnUnsubcribe.Width = 100;
                        btnUnsubcribe.Location = new Point(x, y);
                        btnUnsubcribe.Click += new EventHandler(btnUnsubcribe_Click);
                        pnlFeeds.Controls.Add(btnUnsubcribe);
                        x += 104;
                        if (j["commands"].ToString().IndexOf("\"dm\"") == -1)
                            y += (btnUnsubcribe.Height + 3);
                    }
                    if (command.Value<string>() == "subscribe")
                    {
                        Button btnSubcribe = new Button();
                        btnSubcribe.Text = Properties.Resources.SUBCRIBE_TEXT;
                        btnSubcribe.Tag = j["id"].Value<string>();
                        btnSubcribe.Width = 100;
                        btnSubcribe.Location = new Point(x, y);
                        btnSubcribe.Click += new EventHandler(btnSubcribe_Click);

                        pnlFeeds.Controls.Add(btnSubcribe);

                        if ((x + 103) > pnlFeeds.Width)
                        {
                            x = 3;
                            y += (2 + btnSubcribe.Height);
                        }
                        else
                        {
                            if (j["commands"].ToString().IndexOf("\"dm\"") == -1)
                                y += (btnSubcribe.Height + 3);
                        }
                    }
                    if (command.Value<string>() == "dm")
                    {
                        Button btnDm = new Button();
                        btnDm.Text = Properties.Resources.DM_TEXT;
                        btnDm.Tag = j["id"].Value<string>();
                        btnDm.Width = 115;
                        btnDm.Location = new Point(x, y);
                        btnDm.Click += new EventHandler(btnDm_Click);
                        pnlFeeds.Controls.Add(btnDm);
                        y += (3 + btnDm.Height);
                    }
                }
                x = 3;
                y += 1;


                foreach (JObject entry in entries)
                {

                    JToken body = entry["rawBody"];
                    JToken url = entry["rawLink"];
                    LinkLabel linkLabel = new LinkLabel();
                    linkLabel.Font = new Font(FontFamily.GenericSansSerif, 9f, FontStyle.Regular);

                    linkLabel.Location = new Point(x, y);
                    linkLabel.Tag = entry["id"].Value<string>();
                    linkLabel.Text = body.Value<string>();
                    linkLabel.Height = CFMeasureString.MeasureString(linkLabel, linkLabel.Text, rect).Height;
                    linkLabel.Click += new EventHandler(linkLabel_Click);
                    pnlFeeds.Controls.Add(linkLabel);
                    linkLabel.Width = rect.Width;
                    y += linkLabel.Size.Height;
                    y += 2;

                    if (id != entry["id"].Value<string>())
                    {
                        int com = 0, like = 0;

                        if (entry["comments"] != null)
                            com = entry["comments"][0]["num"] == null ? entry["comments"].Count() : entry["comments"][0]["num"].Value<int>();
                        if (entry["likes"] != null)
                            like = entry["likes"][0]["num"] == null ? entry["likes"].Count() : entry["likes"][0]["num"].Value<int>();// entry["likes"][0]["num"].Value<int>();


                        if (com != 0 || like != 0)
                        {
                            LinkLabel lblCommentsAndLinks = new LinkLabel();
                            lblCommentsAndLinks.Text = string.Format(Properties.Resources.COMMENT_LINK_SUMMARY, com, like);
                            lblCommentsAndLinks.Location = new Point(x, y);
                            lblCommentsAndLinks.Font = new Font(FontFamily.GenericSansSerif, 8f, FontStyle.Italic);
                            lblCommentsAndLinks.Width = rect.Width;
                            lblCommentsAndLinks.Height = CFMeasureString.MeasureString(lblCommentsAndLinks, lblCommentsAndLinks.Text, rect).Height;
                            lblCommentsAndLinks.Click += new EventHandler(lblCommentsAndLinks_Click);

                            lblCommentsAndLinks.Tag = entry["id"].Value<string>() + "|" + curPos;
                            lblCommentsAndLinks.ForeColor = Color.Gray;

                            y += lblCommentsAndLinks.Size.Height;
                            pnlFeeds.Controls.Add(lblCommentsAndLinks);
                        }
                        y += 1;
                    }
                    else if (id == entry["id"].Value<string>())
                    {
                        JArray comments = (JArray)entry["comments"];
                        if (comments != null)
                        {
                            JToken comment;
                            comment = comments[0];
                            int nameY = y, nameX = x;
                            nameX = 20;
                            while (comment != null)
                            {

                                if (comment["id"] != null)
                                {

                                    PictureBox pb = new PictureBox();
                                    pb.Image = Properties.Resources.comment1;
                                    pb.Size = Properties.Resources.comment1.Size;
                                    pb.Location = new Point(x, nameY);
                                    pnlFeeds.Controls.Add(pb);

                                    JToken commentFrom = comment["from"];
                                    Label lblComment = new Label();
                                    lblComment.Text = string.Format("{0}", comment["rawBody"].Value<string>());
                                    lblComment.Location = new Point(nameX, nameY);
                                    lblComment.Font = new Font(FontFamily.GenericSerif, 8f, FontStyle.Regular);
                                    lblComment.Width = rect.Width;
                                    lblComment.Height = CFMeasureString.MeasureString(lblComment, lblComment.Text, rect).Height;

                                    nameY += lblComment.Size.Height + 1;
                                    pnlFeeds.Controls.Add(lblComment);

                                    LinkLabel lblCommentUser = new LinkLabel();
                                    lblCommentUser.Text = commentFrom["name"].Value<string>();
                                    lblCommentUser.Tag = commentFrom["id"].Value<string>();
                                    lblCommentUser.Click += new EventHandler(lblComment_Click);
                                    lblCommentUser.Width = rect.Width - 30;
                                    lblCommentUser.TextAlign = ContentAlignment.TopRight;
                                    lblCommentUser.Location = new Point(nameX, nameY);
                                    pnlFeeds.Controls.Add(lblCommentUser);
                                    nameY += lblCommentUser.Size.Height + 1;

                                }
                                else
                                {
                                    LinkLabel lblCommentsAndLinks = new LinkLabel();
                                    lblCommentsAndLinks.Text = comment["body"].Value<string>();
                                    lblCommentsAndLinks.Location = new Point(nameX, nameY);
                                    lblCommentsAndLinks.Font = new Font(FontFamily.GenericSansSerif, 8f, FontStyle.Italic);
                                    lblCommentsAndLinks.Width = rect.Width;
                                    lblCommentsAndLinks.Height = CFMeasureString.MeasureString(lblCommentsAndLinks, lblCommentsAndLinks.Text, rect).Height;
                                    nameY += lblCommentsAndLinks.Size.Height + 1;
                                    pnlFeeds.Controls.Add(lblCommentsAndLinks);

                                }

                                comment = comment.Next;
                            }
                            y = (nameY + 1);
                        }

                        JArray likes = (JArray)entry["likes"];
                        if (likes != null)
                        {
                            JToken like;
                            like = likes[0];
                            int nameY = y, nameX = x;
                            nameX = 20;
                            Label lbl = new Label();
                            List<string> sb = new List<string>();
                            while (like != null)
                            {
                                if (like["from"] != null)
                                {
                                    JToken likeFrom = like["from"];
                                    sb.Add(likeFrom["name"].Value<string>());
                                }
                                else
                                    sb.Add(like["body"].Value<string>());
                                like = like.Next;
                            }
                            string veriler = string.Join(", ", sb.ToArray());
                            lbl.Text = veriler;
                            int height = CFMeasureString.MeasureString(lbl, lbl.Text, rect).Height;
                            // y += nameY + 2;
                            PictureBox pbLike = new PictureBox();
                            pbLike.Image = Properties.Resources.smile1;
                            pbLike.Size = Properties.Resources.smile1.Size;
                            pbLike.Location = new Point(x, nameY);
                            pnlFeeds.Controls.Add(pbLike);
                            lbl.Font = new Font(FontFamily.GenericSerif, 8f, FontStyle.Regular);
                            lbl.Width = rect.Width;
                            lbl.Height = height;
                            lbl.Location = new Point(nameX, nameY);
                            pnlFeeds.Controls.Add(lbl);

                            y = (nameY + height + 3);
                        }


                    }
                    //y += 1;
                    //System.Drawing.Pen p = new Pen(Color.Red);               
                    //p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;              
                    //pnlFeeds.CreateGraphics().DrawLine(p, x, y, rect.Width - 10, y);
                    //y += 1;
                    if (GF.ShowPics)
                    {
                        if (entry["thumbnails"] != null)
                        {
                            foreach (JToken pic in entry["thumbnails"])
                            {
                                PictureBox pb = new PictureBox();
                                Image i = GF.DownloadImage(pic["url"].Value<string>());
                                pb.Image = i;

                                int picX = i.Width;
                                if (picX > (pnlFeeds.Width - 13))
                                    picX = pnlFeeds.Width - 13;

                                pb.Width = picX;
                                pb.Height = i.Height;
                                pb.SizeMode = PictureBoxSizeMode.StretchImage;

                                pb.Tag = pic["link"].Value<string>();
                                pb.Click += new EventHandler(pb_Click);
                                pb.Location = new Point(x, y);
                                y += (pb.Height + 3);
                                pnlFeeds.Controls.Add(pb);
                            }
                        }
                    }
                }

                y += 4;
                LinkLabel lblPrevious = new LinkLabel();
                lblPrevious.Text = Properties.Resources.PREVIOUS;
                lblPrevious.Height = CFMeasureString.MeasureString(lblPrevious, lblPrevious.Text, rect).Height;
                lblPrevious.Tag = (curPos - GF.PageRecordCount) >= 0 ? curPos : 0;
                lblPrevious.Enabled = (curPos - GF.PageRecordCount) >= 0 ? true : false;
                lblPrevious.Click += new EventHandler(lblPager_Click);
                lblPrevious.Width = (rect.Width / 2);
                lblPrevious.Location = new Point(x, y);
                pnlFeeds.Controls.Add(lblPrevious);
                x += lblPrevious.Width;

                LinkLabel lblNext = new LinkLabel();
                lblNext.Text = Properties.Resources.NEXT;
                lblNext.Height = CFMeasureString.MeasureString(lblNext, lblNext.Text, rect).Height;
                int count = FF.ReadUserFeedCount(username);
                lblNext.TextAlign = ContentAlignment.TopRight;
                lblNext.Tag = count > (curPos + GF.PageRecordCount) ? (curPos + GF.PageRecordCount) : 0;
                lblNext.Enabled = count > (curPos + GF.PageRecordCount) ? true : false;
                lblNext.Click += new EventHandler(lblPager_Click);
                lblNext.Width = (rect.Width / 2);
                lblNext.Location = new Point(x, y);
                pnlFeeds.Controls.Add(lblNext);
               
            }
            else
            {
                Label lbl = new Label();
                lbl.Text = Properties.Resources.FORBIDDEN_FEED;
                lbl.Height = CFMeasureString.MeasureString(lbl, lbl.Text, pnlFeeds.ClientRectangle).Height;
                lbl.Width = pnlFeeds.Width;
                lbl.Location = new Point(3, 3);
                pnlFeeds.Controls.Add(lbl);

                Button btn = new Button();
                btn.Text = Properties.Resources.REQUEST_SUBSCRIBE;
                btn.Width = 115;
                btn.Location = new Point(3, lbl.Height + 6);
                btn.Click += new EventHandler(btn_Click);
                btn.Height = 22;
                pnlFeeds.Controls.Add(btn);
            }
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
        }

        void btn_Click(object sender, EventArgs e)
        {
            frmSubscribeAndUnsubscribe frm = new frmSubscribeAndUnsubscribe(frmSubscribeAndUnsubscribe.Subscription.Subscribe, username, null);
            frm.Show();
        }

        void linkLabel_Click(object sender, EventArgs e)
        {
            LinkLabel lbl = (LinkLabel)sender;
            frmEntry frm = new frmEntry(lbl.Tag.ToString());
            frm.Show();
        }
        void pb_Click(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe", pb.Tag.ToString());
            Process.Start(startInfo);
        }
        void lblPager_Click(object sender, EventArgs e)
        {
            LinkLabel lbl = (LinkLabel)sender;
            ReadUserFeeds(username, (int)lbl.Tag);
        }

        void btnDm_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            frmFeed frm = new frmFeed(btn.Tag.ToString());
            frm.ShowDialog();
        }

        void btnSubcribe_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            frmSubscribeAndUnsubscribe frm = new frmSubscribeAndUnsubscribe(frmSubscribeAndUnsubscribe.Subscription.Subscribe,btn.Tag.ToString(), null);
            frm.ShowDialog();
            menuItem3_Click(null, null);
        }

        void btnUnsubcribe_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            frmSubscribeAndUnsubscribe frm = new frmSubscribeAndUnsubscribe(frmSubscribeAndUnsubscribe.Subscription.Unsubscribe, btn.Tag.ToString(), null);
            frm.ShowDialog();
            menuItem3_Click(null, null);
        }

        void lblComment_Click(object sender, EventArgs e)
        {
            LinkLabel lbl = (LinkLabel)sender;
            frmUserForm frm = new frmUserForm(lbl.Tag.ToString());
            frm.Show();
        }



        void lblCommentsAndLinks_Click(object sender, EventArgs e)
        {
            LinkLabel link = (LinkLabel)sender;
            if (link.Tag != null)
            {
                string[] tags = link.Tag.ToString().Split('|');
                ReadUserFeeds(tags[0], Convert.ToInt32(tags[1]));
            }
        }

        void user_Click(object sender, EventArgs e)
        {
            LinkLabel link = (LinkLabel)sender;
            using (Process p = new Process())
            {
                ProcessStartInfo sInfo = new ProcessStartInfo(link.Tag.ToString(), "");
                p.StartInfo = sInfo;
                try
                {
                    p.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(Resources.IE_START_ERROR);
                }
            }


        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            ReadUserFeeds();
        }

        private void miMe_Click(object sender, EventArgs e)
        {
            username = "me";
            ReadUserFeeds();
        }

        private void miEnterFeed_Click(object sender, EventArgs e)
        {
            frmFeed frm = new frmFeed();
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                username = "me";
                ReadUserFeeds();
            }
        }

        private void menuItem3_Click_1(object sender, EventArgs e)
        {
            frmAbout frm = new frmAbout();
            frm.Show();
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            frmSettings frm = new frmSettings();
            frm.ShowDialog();
        }

       
        
        
    }
}